package com.java.second_goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.second_goods.common.utils.StringUtils;
import com.java.second_goods.entity.Goods;
import com.java.second_goods.entity.GoodsImage;
import com.java.second_goods.mapper.GoodsMapper;
import com.java.second_goods.service.IGoodsImageService;
import com.java.second_goods.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品 服务层实现
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private IGoodsImageService goodsImageService;

    /**
     * 查询商品信息
     *
     * @param id 商品ID
     * @return 商品信息
     */
    @Override
    public Goods selectGoodsById(Integer id) {
        return goodsMapper.selectById(id);
    }

    /**
     * 查询商品列表
     *
     * @param goods 商品信息
     * @return 商品集合
     */
    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        if (goods != null) {
            // 构建查询条件
            if (StringUtils.isNotEmpty(goods.getName())) {
                queryWrapper.like(Goods::getName, goods.getName());
            }
            if (goods.getCategoryId() != null) {
                queryWrapper.eq(Goods::getCategoryId, goods.getCategoryId());
            }
            if (goods.getIsPopular() != null) {
                queryWrapper.eq(Goods::getIsPopular, goods.getIsPopular());
            }
            if (goods.getIsNew() != null) {
                queryWrapper.eq(Goods::getIsNew, goods.getIsNew());
            }
            if (goods.getCondition() != null) {
                queryWrapper.eq(Goods::getCondition, goods.getCondition());
            }
            if (goods.getSellerId() != null) {
                queryWrapper.eq(Goods::getSellerId, goods.getSellerId());
            }
            if (StringUtils.isNotEmpty(goods.getLocation())) {
                queryWrapper.like(Goods::getLocation, goods.getLocation());
            }
            if (StringUtils.isNotEmpty(goods.getTags())) {
                queryWrapper.like(Goods::getTags, goods.getTags());
            }
            if (goods.getNegotiable() != null) {
                queryWrapper.eq(Goods::getNegotiable, goods.getNegotiable());
            }
            if (goods.getTransactionType() != null) {
                queryWrapper.eq(Goods::getTransactionType, goods.getTransactionType());
            }
            if (goods.getStatus() != null) {
                queryWrapper.eq(Goods::getStatus, goods.getStatus());
            }
        }
        // 默认只查询正常状态的商品
        if (goods == null || goods.getStatus() == null) {
            queryWrapper.eq(Goods::getStatus, 1);
        }
        // 按照创建时间倒序排序
        queryWrapper.orderByDesc(Goods::getCreateTime);

        return goodsMapper.selectList(queryWrapper);
    }

    /**
     * 查询热门商品列表
     *
     * @param limit 限制条数
     * @return 商品列表
     */
    @Override
    public List<Goods> selectPopularGoods(Integer limit) {
        return goodsMapper.selectPopularGoods(limit);
    }

    /**
     * 查询新品列表
     *
     * @param limit 限制条数
     * @return 商品列表
     */
    @Override
    public List<Goods> selectNewGoods(Integer limit) {
        return goodsMapper.selectNewGoods(limit);
    }

    /**
     * 查询用户发布的商品列表
     *
     * @param sellerId 卖家ID
     * @return 商品列表
     */
    @Override
    public List<Goods> selectGoodsBySellerId(Integer sellerId) {
        return goodsMapper.selectGoodsBySellerId(sellerId);
    }

    /**
     * 新增商品
     *
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGoods(Goods goods) {
        // 设置默认值
        if (goods.getStatus() == null) {
            goods.setStatus(1);
        }
        if (goods.getViewsCount() == null) {
            goods.setViewsCount(0);
        }
        if (goods.getFavoritesCount() == null) {
            goods.setFavoritesCount(0);
        }
        if (goods.getIsPopular() == null) {
            goods.setIsPopular(false);
        }
        if (goods.getIsNew() == null) {
            goods.setIsNew(true);
        }
        if (goods.getNegotiable() == null) {
            goods.setNegotiable(0);
        }
        if (goods.getQuantity() == null) {
            goods.setQuantity(1);
        }

        return goodsMapper.insert(goods);
    }

    /**
     * 修改商品
     *
     * @param goods 商品信息
     * @return 结果
     */
    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateById(goods);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteGoodsById(Integer id) {
        // 删除商品图片
        goodsImageService.deleteImagesByGoodsId(id);

        // 逻辑删除商品（将状态设为0）
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus(0);
        return goodsMapper.updateById(goods);
    }

    /**
     * 批量删除商品信息
     *
     * @param ids 需要删除的商品ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteGoodsByIds(Integer[] ids) {
        // 删除商品图片
        for (Integer id : ids) {
            goodsImageService.deleteImagesByGoodsId(id);
        }

        // 逻辑删除商品（将状态设为0）
        List<Goods> goodsList = new ArrayList<>();
        for (Integer id : ids) {
            Goods goods = new Goods();
            goods.setId(id);
            goods.setStatus(0);
            goodsList.add(goods);
        }
        return updateBatchById(goodsList) ? ids.length : 0;
    }

    /**
     * 增加商品浏览次数
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int increaseViewCount(Integer id) {
        return goodsMapper.increaseViewCount(id);
    }

    /**
     * 增加商品收藏次数
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int increaseFavoriteCount(Integer id) {
        return goodsMapper.increaseFavoriteCount(id);
    }

    /**
     * 减少商品收藏次数
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int decreaseFavoriteCount(Integer id) {
        return goodsMapper.decreaseFavoriteCount(id);
    }

    /**
     * 上架商品
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int publishGoods(Integer id) {
        return goodsMapper.updateGoodsStatus(id, 1);
    }

    /**
     * 下架商品
     *
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int unpublishGoods(Integer id) {
        return goodsMapper.updateGoodsStatus(id, 0);
    }

    /**
     * 按分类统计商品数量
     *
     * @return 统计结果
     */
    @Override
    public List<Map<String, Object>> countGoodsByCategory() {
        // 确保 Mapper 返回的是 Map 列表
        List<Map<String, Object>> result = goodsMapper.countGoodsByCategory();
        List<Map<String, Object>> categoryStats = new ArrayList<>();

        for (Map<String, Object> row : result) {
            Map<String, Object> map = new HashMap<>();
            // 直接从 Map 中获取键值，确保键名与查询结果一致
            map.put("category", row.get("category"));
            map.put("count", row.get("count"));
            categoryStats.add(map);
        }

        return categoryStats;
    }
}